package com.zone.vehicle.superApps.view.home.app;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.zone.vehicle.lib.search.FloatingSearchView;
import com.zone.vehicle.lib.search.suggestions.SearchSuggestionsAdapter;
import com.zone.vehicle.lib.search.suggestions.model.SearchSuggestion;
import com.zone.sdk.module.comment.entity.SearchResultEntity;
import com.zone.vehicle.superApps.bean.SuperSearchSuggestion;
import com.zone.vehicle.superApps.databinding.FragmentHomeAppBinding;
import com.zone.vehicle.superApps.model.HomeViewModel;
import com.zone.vehicle.superApps.model.ViewModelFactory;
import com.zone.vehicle.superApps.view.common.base.BaseFragment;
import com.zone.vehicle.superApps.view.common.listener.ActionEnum;
import com.zone.vehicle.superApps.view.common.listener.ActionListener;
import com.zone.vehicle.superApps.view.home.app.main.AppHorizontalFragment;
import com.zone.vehicle.superApps.view.home.app.search.SearchResultFragment;

import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.zone.vehicle.superApps.view.common.listener.ActionEnum.ACTION_BIND_SUGGESTION;
import static com.zone.vehicle.superApps.view.common.listener.ActionEnum.ACTION_FOCUS_CLEARED;
import static com.zone.vehicle.superApps.view.common.listener.ActionEnum.ACTION_SEARCH_FOCUS;
import static com.zone.vehicle.superApps.view.common.listener.ActionEnum.ACTION_SEARCH_TEXT_CHANGED;
import static com.zone.vehicle.superApps.view.home.HomeFragment.RECOMMEND_FRAGMENT;

public class HomeAppFragment extends BaseFragment {

    private static final String TAG = HomeAppFragment.class.getSimpleName();

    private FragmentHomeAppBinding binding;

    private HomeViewModel viewModel;

//    public static final String APP_HORIZONTAL_FRAGMENT = AppHorizontalFragment.class.getSimpleName();
    public static final String APP_HORIZONTAL_FRAGMENT = "AppHorizontalFragment";
//    public static final String SEARCH_RESULT_FRAGMENT = SearchResultFragment.class.getSimpleName();
    public static final String SEARCH_RESULT_FRAGMENT = "SearchResultFragment";

    private FragmentPagerAdapter adapter;

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentHomeAppBinding.inflate(inflater);
        init();
//        changePage(APP_HORIZONTAL_FRAGMENT);
        return binding.getRoot();
    }

    @Override
    public void initFragmentPages() {
        super.initFragmentPages();
        addPage(new AppHorizontalFragment());
        addPage(new SearchResultFragment());
    }

    private void init(){
        viewModel = new ViewModelProvider(requireActivity() , new ViewModelFactory()).get(HomeViewModel.class);

        binding.recommend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "recommend onClick="+v);
                changePage(RECOMMEND_FRAGMENT);
            }
        });
        initFloatingSearch();

        addListener(new ActionListener() {
            @Override
            public boolean onAction(ActionEnum action) {
                Log.d(TAG, "onAction="+ action);
//                if (action == ACTION_FOCUS_CLEARED){
//                    binding.viewpager.setCurrentItem(0);
//                    return true;
//                }else
                if (action == ACTION_SEARCH_FOCUS){
                    binding.viewpager.setCurrentItem(1);
                    return true;
                }
                return false;
            }

            @Override
            public boolean onPageChanged(String pageName) {
                Log.d(TAG, "onPageChanged="+ pageName);
                return innerChangedPage(pageName);
            }
        });
        adapter = new FragmentPagerAdapter(getChildFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @Override
            public int getCount() {
                return getPages().size();
            }

            @NonNull
            @Override
            public Fragment getItem(int position) {
                return getPage(position);
            }
        };
        binding.viewpager.setAdapter(adapter);
    }

    private boolean innerChangedPage(String pageName) {
        switch (pageName){
            case APP_HORIZONTAL_FRAGMENT:
                binding.viewpager.setCurrentItem(0);
                return true;
            case SEARCH_RESULT_FRAGMENT:
                binding.viewpager.setCurrentItem(1);
                return true;
            default:
                return false;
        }
    }

    private void initFloatingSearch(){
        binding.floatingSearch.setBackgroundColor(Color.TRANSPARENT);
        binding.floatingSearch.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
            @Override
            public void onSearchTextChanged(String oldQuery, String newQuery) {
                onAction(ACTION_SEARCH_TEXT_CHANGED);
                if (!oldQuery.equals("") && newQuery.equals("")) {
                    changePage(APP_HORIZONTAL_FRAGMENT);
                    binding.floatingSearch.clearSuggestions();
                } else {
                    viewModel.indexSearch(newQuery);
                }
                Log.d(TAG, "onSearchTextChanged()");
            }
        });
        binding.floatingSearch.setOnClearSearchActionListener(new FloatingSearchView.OnClearSearchActionListener() {
            @Override
            public void onClearSearchClicked() {
                binding.viewpager.setCurrentItem(0);
            }
        });
        binding.floatingSearch.setOnHomeActionClickListener(new FloatingSearchView.OnHomeActionClickListener() {
            @Override
            public void onHomeClicked() {
                binding.viewpager.setCurrentItem(0);
            }
        });
        viewModel.getSearchAppList().observe(getViewLifecycleOwner(), new Observer<List<SearchResultEntity>>() {
            @Override
            public void onChanged(List<SearchResultEntity> appEntities) {
                if (ObjectUtils.isNotEmpty(appEntities)){
                    List<SuperSearchSuggestion> searchSuggestions = new ArrayList<>();
                    for (int i=0; i<appEntities.size(); i++){
                        SearchResultEntity appEntity = appEntities.get(i);
                        SuperSearchSuggestion suggestion = new SuperSearchSuggestion();
                        suggestion.setSearch(appEntity.getName());
                        searchSuggestions.add(suggestion);
                    }
                    binding.floatingSearch.swapSuggestions(searchSuggestions);
                    binding.floatingSearch.hideProgress();
                }

            }
        });
        binding.floatingSearch.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
            @Override
            public void onSuggestionClicked(final SearchSuggestion searchSuggestion) {
                viewModel.setSearchData(searchSuggestion.getBody());
//                binding.floatingSearch.hideProgress();
                binding.floatingSearch.clearSuggestions();
//                onAction(ACTION_SUGGESTION_CLICKED);
                changePage(SEARCH_RESULT_FRAGMENT);
//                onPageChanged(SEARCH_RESULT_FRAGMENT);
//                searchResultsListAdapter.swapData(getTestData());
//                ColorSuggestion colorSuggestion = (ColorSuggestion) searchSuggestion;
//                DataHelper.findColors(getActivity(), colorSuggestion.getBody(),
//                        new DataHelper.OnFindColorsListener() {
//
//                            @Override
//                            public void onResults(List<ColorWrapper> results) {
//                                //show search results
//                            }
//
//                        });
                Log.d(TAG, "onSuggestionClicked()");
            }

            @Override
            public void onSearchAction(String query) {
//                onAction(ACTION_SEARCH);
                changePage(SEARCH_RESULT_FRAGMENT);
                Log.d(TAG, "onSearchAction()");
            }
        });

        binding.floatingSearch.setOnFocusChangeListener(new FloatingSearchView.OnFocusChangeListener() {
            @Override
            public void onFocus() {
                onAction(ACTION_SEARCH_FOCUS);
//                changePage(SEARCH_RESULT_FRAGMENT);
                Log.d(TAG, "onFocus()");
            }

            @Override
            public void onFocusCleared() {
//                onBack();
                onAction(ACTION_FOCUS_CLEARED);
                //set the title of the bar so that when focus is returned a new query begins
//                binding.floatingSearch.setSearchBarTitle(mLastQuery);
                Log.d(TAG, "onFocusCleared()");
            }
        });

        binding.floatingSearch.setOnBindSuggestionCallback(new SearchSuggestionsAdapter.OnBindSuggestionCallback() {
            @Override
            public void onBindSuggestion(View suggestionView, ImageView leftIcon,
                                         TextView textView, SearchSuggestion item, int itemPosition) {
                onAction(ACTION_BIND_SUGGESTION);
//                ColorSuggestion colorSuggestion = (ColorSuggestion) item;
//
//                String textColor = mIsDarkSearchTheme ? "#ffffff" : "#000000";
//                String textLight = mIsDarkSearchTheme ? "#bfbfbf" : "#787878";
//
//                if (colorSuggestion.getIsHistory()) {
//                    leftIcon.setImageDrawable(ResourcesCompat.getDrawable(getResources(),
//                            R.drawable.ic_history_black_24dp, null));
//
//                    Util.setIconColor(leftIcon, Color.parseColor(textColor));
//                    leftIcon.setAlpha(.36f);
//                } else {
//                    leftIcon.setAlpha(0.0f);
//                    leftIcon.setImageDrawable(null);
//                }
//
//                textView.setTextColor(Color.parseColor(textColor));
//                String text = colorSuggestion.getBody()
//                        .replaceFirst(mSearchView.getQuery(),
//                                "<font color=\"" + textLight + "\">" + mSearchView.getQuery() + "</font>");
//                textView.setText(Html.fromHtml(text));
            }

        });
    }

}